import { defineStore } from "pinia";
import { useStorage } from "@vueuse/core";
import defaultSettings from "@/settings";
import { AbpConfig } from '@/api/abp/types';
import {getApplicationConfiguration} from '@/api/abp/abp';
import { store } from "@/store";
import {setLocale} from  "@/lang/index";
// 导入 Element Plus 中英文语言包
import zhCn from "element-plus/es/locale/lang/zh-cn";
import en from "element-plus/es/locale/lang/en";

// setup
export const useAppStore = defineStore("app", () => {
  // state
  const device = useStorage("device", "desktop");
  const size = useStorage<any>("size", defaultSettings.size);
  const language = useStorage("language", defaultSettings.language);

  const sidebarStatus = useStorage("sidebarStatus", "closed");
  
  const abpConfig=useStorage<AbpConfig>("abpConfig",null);
  
  const sidebar = reactive({
    opened: sidebarStatus.value !== "closed",
    withoutAnimation: false,
  });

  /**
   * 根据语言标识读取对应的语言包
   */
  const locale = computed(() => {
    if (language?.value == "en") {
      return en;
    } else {
      return zhCn;
    }
  });




  // actions
function   applicationConfiguration() {
  return new Promise<AbpConfig>((resolve, reject) => {
    getApplicationConfiguration()
      .then(response => {
        abpConfig.value=response;
        const language= response.localization.currentCulture.cultureName;
        const values=response.localization.values;
        //console.log('response',response)
        setLocale(language,values);
        resolve(response)
       
      })
      .catch(error => {
        reject(error)
      })
  })
}


  function toggleSidebar(withoutAnimation: boolean) {
    sidebar.opened = !sidebar.opened;
    sidebar.withoutAnimation = withoutAnimation;
    if (sidebar.opened) {
      sidebarStatus.value = "opened";
    } else {
      sidebarStatus.value = "closed";
    }
  }

  function closeSideBar(withoutAnimation: boolean) {
    sidebar.opened = false;
    sidebar.withoutAnimation = withoutAnimation;
    sidebarStatus.value = "closed";
  }

  function openSideBar(withoutAnimation: boolean) {
    sidebar.opened = true;
    sidebar.withoutAnimation = withoutAnimation;
    sidebarStatus.value = "opened";
  }

  function toggleDevice(val: string) {
    device.value = val;
  }

  function changeSize(val: string) {
    size.value = val;
  }
  /**
   * 切换语言
   *
   * @param val
   */
  function changeLanguage(val: string) {
    language.value = val;
  }

  return {
    device,
    sidebar,
    language,
    locale,
    size,
    applicationConfiguration,
    toggleDevice,
    changeSize,
    changeLanguage,
    toggleSidebar,
    closeSideBar,
    openSideBar,
    abpConfig
  };
});


export function useAppStoreHook() {
  return useAppStore(store);
}

